package com.a16.yuejian.yuejian.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.a16.yuejian.yuejian.R;
import com.a16.yuejian.yuejian.javabean.Exist;
import com.a16.yuejian.yuejian.javabean.Success;
import com.a16.yuejian.yuejian.listener.ExistListener;
import com.a16.yuejian.yuejian.listener.SuccessListener;
import com.a16.yuejian.yuejian.model.UserModel;
import com.mob.MobSDK;

import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import static com.a16.yuejian.yuejian.R.id.videoView;

public class RegActivity extends AppCompatActivity implements View.OnClickListener,SuccessListener, View.OnFocusChangeListener,ExistListener {
    private EditText phone,username,pwd,pwd1,code;
    private TextView error;
    private Button reg,send,head;
    private ImageView back,img;
    private String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "mms";
    private File photo_file = new File(path);
    private String picPath = null;
    static int CODE_ING=61;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reg);
        initViews();
        initEvents();
        initSDK();
    }

    private void initSDK() {
        MobSDK.init(this, "215493f9d0e84", "2ec2b15d4a4c0788279cf3eefeade3c8");
        EventHandler eventHandler = new EventHandler(){
            public void afterEvent(int event, int result, Object data) {
                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eventHandler);
    }

    Handler handler = new Handler(){
        public void handleMessage(Message msg){
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            if (CODE_ING !=0 ){
                send.setText(CODE_ING + "s后重发");
            }else if (CODE_ING ==0){
                send.setText("重新发送");
                send.setClickable(true);
            }else {
                send.setText("获取验证码");
                send.setClickable(true);
            }
            if (result==SMSSDK.RESULT_COMPLETE){
                if (event==SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE){
//                    UserModel userModel = new UserModel();
//                    userModel.reg(phone.getText().toString(),username.getText().toString(),pwd.getText().toString(),picPath,RegActivity.this);
                }else if (event==SMSSDK.EVENT_GET_VERIFICATION_CODE){
                    Toast.makeText(getApplicationContext(), "验证码已经发送",Toast.LENGTH_SHORT).show();
                } else {
                    ((Throwable) data).printStackTrace();
                }
            }
            if(result==SMSSDK.RESULT_ERROR){
                try {
                    Throwable throwable = (Throwable) data;
                    throwable.printStackTrace();
                    JSONObject object = new JSONObject(throwable.getMessage());
                    String des = object.optString("detail");
                    int status = object.optInt("status");
                    if (status > 0 && !TextUtils.isEmpty(des)) {
                        Toast.makeText(getApplicationContext(), des, Toast.LENGTH_SHORT).show();
                        return;
                    }
                } catch (Exception e) {

                }
            }

        }
    };

    private void initEvents() {
        phone.setOnFocusChangeListener(this);
        send.setOnClickListener(this);
        back.setOnClickListener(this);
        head.setOnClickListener(this);
    }

    private void initViews() {
        phone =(EditText)findViewById(R.id.reg_phone);
        username =(EditText)findViewById(R.id.reg_username);
        code=(EditText)findViewById(R.id.reg_yanzen);
        pwd =(EditText)findViewById(R.id.reg_pwd);
        pwd1 =(EditText)findViewById(R.id.reg_pwd1);
        reg =(Button)findViewById(R.id.reg_reg);
        send =(Button)findViewById(R.id.reg_send);
        head =(Button)findViewById(R.id.reg_head);
        error=(TextView)findViewById(R.id.error);
        back = (ImageView)findViewById(R.id.reg_back);
        img = (ImageView)findViewById(R.id.reg_img);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.reg_reg:
                if (phone.getText().toString()!=null&&"".equals(phone.getText().toString())){
                    error.setText("请输入手机号！");
                }else if(username.getText().toString()!=null&&"".equals(username.getText().toString())){
                    error.setText("请输入昵称！");
                }else if (pwd.getText().toString()!=null&&"".equals(pwd.getText().toString())){
                    error.setText("请输入密码！");
                }else if (!pwd1.getText().toString().equals(pwd.getText().toString())){
                    error.setText("确认密码和密码不一致！");
                }else{
//                    SMSSDK.submitVerificationCode("86",phone.getText().toString(),code.getText().toString());
                    UserModel userModel = new UserModel();
                    userModel.reg(phone.getText().toString(),username.getText().toString(),pwd.getText().toString(),picPath,RegActivity.this);
                }
                break;
            case R.id.reg_send:
                SMSSDK.getVerificationCode("86",phone.getText().toString());
                send.setClickable(false);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i=60;i>=0;i--){
                            CODE_ING = i;
                            handler.sendEmptyMessage(CODE_ING);
                            try {
                                Thread.sleep(1000);
                            }catch (InterruptedException e){
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
                break;
            case R.id.reg_back:
                finish();
                break;
            case R.id.reg_head:
                final CharSequence[] items = {"相册","拍照"};
                new AlertDialog.Builder(RegActivity.this).setTitle("选择获取头像方式").setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which==0){
                            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.setType("image/*");
                            startActivityForResult(intent,1);
                        }else {
                            String state=Environment.getExternalStorageState();
                            if(state.equals(Environment.MEDIA_MOUNTED)){
                                Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
                                startActivityForResult(intent,2);
                            } else{
                                Toast.makeText(getApplicationContext(),"请确认已经插入SD卡",Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                }).create().show();
                break;
        }
    }

    @Override
    public void onResponse(Success success) {
        if (success.getSuccess().equals("1")){
            Toast.makeText(RegActivity.this,"注册成功", Toast.LENGTH_SHORT).show();
            Intent intent =new Intent(RegActivity.this,LoginActivity.class);
            startActivity(intent);
            finish();
        }else {
            Toast.makeText(RegActivity.this,"注册失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onResponse(Exist success) {
        if(success.getSuccess().equals("1")){
            error.setText("手机号已注册");
            reg.setEnabled(false);
            reg.setBackgroundResource(R.drawable.ic_unclick);
            reg.setTextColor(Color.parseColor("#ffffff"));
        }else {
            error.setText("");
            reg.setOnClickListener(this);
            reg.setEnabled(true);
            reg.setBackgroundResource(R.drawable.ic_button);
        }
    }

    @Override
    public void onFail() {

    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus){

        }else {
            if (phone.getText().toString()!=null&&"".equals(phone.getText().toString())){
                error.setText("手机号不能为空");
            }else {
                UserModel userModel = new UserModel();
                userModel.exist(phone.getText().toString(),this);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode== Activity.RESULT_OK){
            switch (requestCode){
                case 1:
                    if (data != null) {
                        Uri uri = data.getData();
                        img.setImageURI(uri);
                        ContentResolver cr = this.getContentResolver();
                        Cursor c = cr.query(uri, null, null, null, null);
                        c.moveToFirst();
                        //这是获取的图片保存在sdcard中的位置
                        picPath = c.getString(c.getColumnIndex("_data"));
                    } else {
                        return;
                    }
                    break;

                case 2:
                    if (data!=null){
                        Bundle extras = data.getExtras();
                        Bitmap bitmap = (Bitmap) extras.get("data");
                        img.setImageBitmap(bitmap);
                    }else {
                        return;
                    }
                    break;
            }
        }
    }
}
